package com.lanyuan.util;

import com.alibaba.fastjson.JSON;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class UploadUtils {

    // 项目根路径下的目录  -- SpringBoot static 目录相当于是根路径下（SpringBoot 默认）
	public static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
	public final static String IMG_PATH_PREFIX = "upload/imgs/"+sdf1.format(new Date())+"/";
	

    public static File getImgDirFile(HttpServletRequest request,String carnum){
        // 构建上传文件的存放 "文件夹" 路径
    	String path = request.getSession().getServletContext().getRealPath("/");
        //String fileDirPath = new String("src/main/resources/" + IMG_PATH_PREFIX);
        String fileDirPath = new String(path+IMG_PATH_PREFIX+carnum);
        
        File fileDir = new File(fileDirPath);
        if(!fileDir.exists()){
            // 递归生成文件夹
            fileDir.mkdirs();
        }
        return fileDir;
    }
    public static String uploadimg(HttpServletRequest request,MultipartFile imgFile,String carnum,int a) throws IOException{
        Map<String ,Object> msg = new HashMap<String ,Object>();
        if (imgFile.isEmpty()) {
            // 设置错误状态码
            msg.put("code","500");
            return JSON.toJSONString(msg);
        }
        // 拿到文件名
        String file = imgFile.getOriginalFilename();
        String filename =carnum+"-"+a+file.substring(file.lastIndexOf("."), file.length());
        //存放上传图片的文件夹
        File fileDir = UploadUtils.getImgDirFile(request,carnum);
        // 输出文件夹绝对路径  -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
        System.out.println(fileDir.getAbsolutePath());

        try {
            String url =fileDir.getAbsolutePath() + File.separator + filename;
            //String url =fileDir.getAbsolutePath() + "/" + filename;
            String url1 =IMG_PATH_PREFIX +carnum + File.separator + filename;
            // 构建真实的文件路径
            File newFile = new File(url);
            System.out.println(newFile.getAbsolutePath());

            // 上传图片到 -》 “绝对路径”
            imgFile.transferTo(newFile);
            msg.put("msg","上传成功!");
            msg.put("url",url1);
            msg.put("code","200");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(msg);
    }

}

